import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import legacy from '@vitejs/plugin-legacy'
import viteCompression from 'vite-plugin-compression'
import { visualizer } from 'rollup-plugin-visualizer'
import TurboConsole from 'unplugin-turbo-console/vite'
import { ViteImageOptimizer } from 'vite-plugin-image-optimizer'
import { cdn } from "vite-plugin-cdn2"
import { HOST, PORT, BASE_PROXY } from './src/config'


/**
 * 将输入路径拼接成完整路径
 * @param {*} url 
 * @returns 
 */
function parsePath(url) {
  return path.resolve(__dirname, url);
}

export default defineConfig(({ command, mode, ssrBuild }) => {
  let env = loadEnv(mode, process.cwd());
  if (command == 'serve') {
    // 开发模式
    return {
      plugins: [
        vue(),
        vueJsx(),
        AutoImport({
          imports: ['vue'],
          resolvers: [ElementPlusResolver(),
         ],
        }),
        Components({
          resolvers: [ElementPlusResolver()],
        }),
        legacy({
          targets: ['defaults', 'not IE 11'],
        }),
        TurboConsole({
          // prefix:'',
          // suffix:''
        }),
        ViteImageOptimizer({
          test: /\.(jpe?g|png|gif|tiff|webp|svg|avif)$/i,
          exclude: undefined,
          include: undefined,
          includePublic: true,
          logStats: true,
          ansiColors: true,
          svg: {
            multipass: true,
            plugins: [
              {
                name: 'preset-default',
                params: {
                  overrides: {
                    cleanupNumericValues: false,
                    removeViewBox: false, // https://github.com/svg/svgo/issues/1128
                  },
                  cleanupIDs: {
                    minify: false,
                    remove: false,
                  },
                  convertPathData: false,
                },
              },
              'sortAttrs',
              {
                name: 'addAttributesToSVGElement',
                params: {
                  attributes: [{ xmlns: 'http://www.w3.org/2000/svg' }],
                },
              },
            ],
          },
          png: {
            // https://sharp.pixelplumbing.com/api-output#png
            quality: 100,
          },
          jpeg: {
            // https://sharp.pixelplumbing.com/api-output#jpeg
            quality: 100,
          },
          jpg: {
            // https://sharp.pixelplumbing.com/api-output#jpeg
            quality: 100,
          },
          tiff: {
            // https://sharp.pixelplumbing.com/api-output#tiff
            quality: 100,
          },
          // gif does not support lossless compression
          // https://sharp.pixelplumbing.com/api-output#gif
          gif: {},
          webp: {
            // https://sharp.pixelplumbing.com/api-output#webp
            lossless: true,
          },
          avif: {
            // https://sharp.pixelplumbing.com/api-output#avif
            lossless: true,
          },
          cache: false,
          cacheLocation: undefined,
        }
        ),
        // cdn({ modules: ["vue","echarts"] }),
      ],
      // 本地服务器配置
      server: {
        // 启动项目自动打开
        // open: true,
        host: HOST || 'localhost',
        // 本地服务器端口
        port: PORT || 5173,
        // 本地代理
        proxy: {
          // 基本代理
          [BASE_PROXY]: {
            // 代理目标        
            target: env.VITE_APP_BASE_API,
            // 转换
            changeOrigin: true,
            // websocket代理
            // ws: true,
            // 重写路径
            rewrite: path => path.replace(new RegExp(`^${BASE_PROXY}`), ''),
          },

        },
      },
      // css: {
      //   preprocessorOptions: {
      //     scss: {
      //       additionalData: '@import "./src/assets/style/main.scss";'
      //     }
      //   },
      // },
      // 基础路径
      base: './',
      // 解析
      resolve: {
        alias: {
          '@': parsePath('./src'),
          '~/': `${path.resolve(__dirname, 'src')}/`,
        },
      },
    };
  } else {
    // 生产模式
    return {
      plugins: [
        vue(),
        vueJsx(),
        AutoImport({
          resolvers: [ElementPlusResolver()],
        }),
        Components({
          resolvers: [ElementPlusResolver()],
        }),
        legacy({
          targets: ['defaults', 'not IE 11'],
        }),
        // gzip静态资源压缩-gzip插件
        viteCompression({
          verbose: true, // 默认即可
          disable: false, // 开启压缩(不禁用)，默认即可
          deleteOriginFile: false, // 删除源文件
          threshold: 5120, // 压缩前最小文件大小
          algorithm: 'gzip', // 压缩算法
          ext: '.gz' // 文件类型
        }),
        visualizer({
          open: true, // 注意这里要设置为true，否则无效，如果存在本地服务端口，将在打包后自动展示
          gzipSize: true,
          file: "stats.html", //分析图生成的文件名
          brotliSize: true
        }),
        ViteImageOptimizer({
          test: /\.(jpe?g|png|gif|tiff|webp|svg|avif)$/i,
          exclude: undefined,
          include: undefined,
          includePublic: true,
          logStats: true,
          ansiColors: true,
          svg: {
            multipass: true,
            plugins: [
              {
                name: 'preset-default',
                params: {
                  overrides: {
                    cleanupNumericValues: false,
                    removeViewBox: false, // https://github.com/svg/svgo/issues/1128
                  },
                  cleanupIDs: {
                    minify: false,
                    remove: false,
                  },
                  convertPathData: false,
                },
              },
              'sortAttrs',
              {
                name: 'addAttributesToSVGElement',
                params: {
                  attributes: [{ xmlns: 'http://www.w3.org/2000/svg' }],
                },
              },
            ],
          },
          png: {
            // https://sharp.pixelplumbing.com/api-output#png
            quality: 100,
          },
          jpeg: {
            // https://sharp.pixelplumbing.com/api-output#jpeg
            quality: 100,
          },
          jpg: {
            // https://sharp.pixelplumbing.com/api-output#jpeg
            quality: 100,
          },
          tiff: {
            // https://sharp.pixelplumbing.com/api-output#tiff
            quality: 100,
          },
          // gif does not support lossless compression
          // https://sharp.pixelplumbing.com/api-output#gif
          gif: {},
          webp: {
            // https://sharp.pixelplumbing.com/api-output#webp
            lossless: true,
          },
          avif: {
            // https://sharp.pixelplumbing.com/api-output#avif
            lossless: true,
          },
          cache: false,
          cacheLocation: undefined,
        }
        ),
        // cdn({ modules: ["vue","echarts"] }),
      ],
      // css: {
      //   preprocessorOptions: {
      //     scss: {
      //       additionalData: '@import "./src/assets/style/main.scss";'
      //     }
      //   },
      // },
      // base: `/${ROUTER_BASE}/`,
      resolve: {
        alias: {
          '@': parsePath('./src'),
          '~/': `${path.resolve(__dirname, 'src')}/`,
        },
      },
      build: {
        rollupOptions: {
          output: {
            // 静态文件按类型分包
            chunkFileNames: 'static/js/[name]-[hash].js',
            entryFileNames: 'static/js/[name]-[hash].js',
            assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
            // 拆包
            manualChunks: {
              // echarts: ['echarts'],
              vue: ['vue', 'vue-router'],
              // xlsx: ['xlsx'],
              elementPlus: ['element-plus'],
              // moment: ['moment'],
            },
          },
        },
        // outDir: ``,
        chunkSizeWarningLimit: 2000,
        minify: 'terser',
        // 打包环境移除console.log，debugger
        terserOptions: {
          compress: {
            drop_console: true,
            drop_debugger: true
          }
        }
      },
    };
  }
});

